import java.util.List;

public class GameController {
    private static GameBoard gameBoard;
    private static ScoreBoard scoreBoard;
    private static LevelManager levelManager;
    private GameFeedbackListener feedbackListener;

    public interface GameFeedbackListener {
        void onGameEvent(String message, int score, int x, int y);
    }
    public GameController(GameBoard gameBoard, ScoreBoard scoreBoard, LevelManager levelManager) {
        GameController.gameBoard = gameBoard;
        GameController.scoreBoard = scoreBoard;
        GameController.levelManager = levelManager;
    }
    public void setFeedbackListener(GameFeedbackListener listener) {
        this.feedbackListener = listener;
    }
    public void setGameBoard(GameBoard gameBoard) {
        GameController.gameBoard = gameBoard;
    }
    public void handleMatch(List<Cell> matchedCells) {
        int score = calculateScore(matchedCells);
        scoreBoard.addScore(score);

        if (feedbackListener != null && !matchedCells.isEmpty()) {
            String message = String.format("消除了%d个%s方块，获得%d分",
                    matchedCells.size(),
                    matchedCells.get(0).getColorName(),
                    score);

            feedbackListener.onGameEvent(
                    message,
                    score,
                    matchedCells.get(0).getX(),
                    matchedCells.get(0).getY()
            );
        }
    }
    private int calculateScore(List<Cell> cells) {
        // 基础分 + 连击奖励
        return cells.size() * 10 * levelManager.getCurrentLevel();
    }
    private static Cell selectedCell;
    public void setupCellSelectionHandlers() {
        for (int row = 0; row < gameBoard.getWidth(); row++) {
            for (int col = 0; col < gameBoard.getHeight(); col++) {
                Cell cell = gameBoard.getCell(row, col);
                cell.getCellPane().setOnMouseClicked(e -> handleCellClick(cell));
            }
        }
    }
    public void handleCellClick(Cell cell) {
        if (selectedCell == null) {
            // 第一次选择
            selectedCell = cell;
            cell.highlight();
        } else {
            // 第二次选择
            selectedCell.unhighlight();

            if (isAdjacent(selectedCell, cell)) {
                // 处理交换逻辑
                handleCellSelection(selectedCell, cell);
            }

            selectedCell = null;
        }
    }
    private static boolean isAdjacent(Cell a, Cell b) {
        int dx = Math.abs(a.getX() - b.getX());
        int dy = Math.abs(a.getY() - b.getY());
        return (dx == 1 && dy == 0) || (dx == 0 && dy == 1);
    }
    public void handleCellSelection(Cell first, Cell second) {
        // 尝试交换单元格
        if (gameBoard.swapCells(first.getX(), first.getY(), second.getX(), second.getY())) {
            // 检查是否有匹配
            List<GameBoard.Match> matches = gameBoard.findMatches();

            if (matches.isEmpty()) {
                // 没有匹配则交换回来
                gameBoard.swapCells(first.getX(), first.getY(), second.getX(), second.getY());
            } else {
                // 处理匹配逻辑
                handleMatches(matches);
            }
        }
    }
    private void handleMatches(List<GameBoard.Match> matches) {
        // 计算总得分
        int totalScore = 0;
        for (GameBoard.Match match : matches) {
            totalScore += match.getCells().size() * 10 * levelManager.getMultiplier();
        }

        // 清除匹配并填充
        int clearedCount = gameBoard.clearMatches();
        gameBoard.fillEmptyCells();
        scoreBoard.addScore(totalScore);

        // 处理连锁反应
        while (gameBoard.hasMatches()) {
            matches = gameBoard.findMatches();
            for (GameBoard.Match match : matches) {
                totalScore += match.getCells().size() * 10 * levelManager.getMultiplier();
            }
            clearedCount = gameBoard.clearMatches();
            gameBoard.fillEmptyCells();
            scoreBoard.addScore(totalScore);
        }

        // 检查关卡进度
        if (scoreBoard.getScore() >= levelManager.getTargetScore()) {
            levelManager.nextLevel();
        }
    }
    public static Cell getSelectedCell() {
        return selectedCell;
    }
    public static void setSelectedCell(Cell cell) {
        selectedCell = cell;
    }
}